package com.xunyin.modules.balance.rest;

import com.github.pagehelper.util.StringUtil;
import com.xunyin.api.ApiResult;
import com.xunyin.api.XunyinException;
import com.xunyin.common.bean.LocalUser;
import com.xunyin.common.interceptor.AuthCheck;
import com.xunyin.enums.*;
import com.xunyin.modules.balance.domain.MtSetting;
import com.xunyin.modules.balance.service.MtBalanceService;
import com.xunyin.modules.balance.service.MtSettingService;
import com.xunyin.modules.balance.service.dto.RechargeRuleDto;
import com.xunyin.modules.balance.service.param.TBalanceParam;
import com.xunyin.modules.log.AppLog;
import com.xunyin.modules.mtorder.domain.MtOrder;
import com.xunyin.modules.mtorder.service.MtOrderService;
import com.xunyin.modules.mtorder.service.dto.OrderDto;
import com.xunyin.modules.mtstore.domain.MtStore;
import com.xunyin.modules.mtstore.service.StoreService;
import com.xunyin.modules.redisqueue.RedisSqueueService;
import com.xunyin.modules.shareorder.param.TShareOrderParam;
import com.xunyin.modules.user.domain.YxUser;
import com.xunyin.modules.user.service.YxUserService;
import com.xunyin.modules.user.service.mapper.SysXbuserMapper;
import com.xunyin.modules.weixin.service.WeixinService;
import com.xunyin.utils.CommonUtilV;
import com.xunyin.web.ResponseObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 余额接口相关controller
 * <p>
 * Created by xunyinyunshang <3594419785@qq.com>
 * CopyRight 讯音云商 https://www.tonetn.com
 */
@Slf4j
@RestController
@Api(value = "余额接口相关", tags = "共享空间:余额接口相关")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ClientBalanceController {

    private final MtSettingService mtSettingService;

    private final MtBalanceService balanceService;

    private final SysXbuserMapper sysXbuserMapper;

    //private final SysXbuserService sysXbuserService;

    private final YxUserService userService;

    //private final TOrderServiceOld tOrderServiceOld;

    private final MtOrderService mtOrderService;

    private final WeixinService weixinService;

    private final StoreService storeService;

    private final RedisSqueueService redisSqueueService;

    /**
     * 查询用户余额
     */
    @AppLog(value = "查询用户余额接口", type = 1)
    //@AuthCheck
    @PostMapping("/getUserInfo")
    @ApiOperation(value = "getUserInfo", notes = "查询用户余额接口")
    public ApiResult<YxUser> getUserInfo(@Validated @RequestBody TShareOrderParam tShareOrderParam) {
        //SysXbuser sysXbuser = sysXbuserService.getById(tShareOrderParam.getUserId());
        YxUser user = userService.getById(tShareOrderParam.getUserId());
        return ApiResult.ok(user);
    }

    /**
     * 充值配置
     */
    @AppLog(value = "充值配置", type = 1)
    //@AuthCheck
    @PostMapping("/recharge/rechargeRuleList")
    @ApiOperation(value = "充值配置", notes = "充值配置")
    public ApiResult<Map<String, Object>> setting(HttpServletRequest request, @RequestBody Map<String, Object> param) {

        Map<String, Object> outParams = new HashMap<>();
        Integer storeId = (param.get("storeId") == null) ? 0 : Integer.parseInt(param.get("storeId").toString());
        List<MtSetting> settingList = mtSettingService.getSettingList(SettingTypeEnum.BALANCE.getKey(), storeId);

        List<RechargeRuleDto> rechargeRuleList = new ArrayList<>();
        String status = StatusEnum.DISABLE.getKey();
        String remark = "";

        if (settingList.size() > 0) {
            for (MtSetting setting : settingList) {
                if (setting.getName().equals(BalanceSettingEnum.RECHARGE_RULE.getKey())) {
                    status = setting.getStatus();
                    String item[] = setting.getValue().split(",");
                    if (item.length > 0) {
                        for (String value : item) {
                            String el[] = value.split("_");
                            if (el.length == 2) {
                                RechargeRuleDto e = new RechargeRuleDto();
                                e.setRechargeAmount(el[0]);
                                e.setGiveAmount(el[1]);
                                int rechargeAmount = el[0] == null ? 0 : Integer.valueOf(el[0]);
                                int giveAmount = el[1] == null ? 0 : Integer.valueOf(el[1]);
                                e.setTotalRechargeAmount(rechargeAmount + giveAmount);
                                rechargeRuleList.add(e);
                            }
                        }
                    }
                } else if (setting.getName().equals(BalanceSettingEnum.RECHARGE_REMARK.getKey())) {
                    remark = setting.getValue();
                }
            }
        }

        outParams.put("rechargeRuleList", rechargeRuleList);
        if (status.equals(StatusEnum.ENABLED.getKey())) {
            outParams.put("isOpen", true);
        } else {
            outParams.put("isOpen", false);
        }
        outParams.put("remark", remark);
        return ApiResult.ok(outParams);
    }


    /**
     * 充值余额
     */
    @AppLog(value = "充值余额", type = 1)
    //@AuthCheck
    @PostMapping("/balance/doRecharge")
    @ApiOperation(value = "充值余额", notes = "充值余额")
    public ApiResult<Map<String, Object>> doRecharge(HttpServletRequest request, @RequestBody TBalanceParam param) {
        //Integer storeId = request.getHeader("storeId") == null ? 0 : Integer.parseInt(request.getHeader("storeId"));
       /*
        String token = request.getHeader("Access-Token");
        if (StringUtil.isEmpty(token)) {
            return getFailureResult(1001);
        }

        UserInfo userInfo = TokenUtil.getUserInfoByToken(token);
        if (null == userInfo) {
            return getFailureResult(1001);
        }*/
        // Integer userId = Integer.parseInt(param.get("userId").toString());
        Integer storeId = param.getStoreId();
        Integer userId = param.getUserId();
        Map<String, Object> data = new HashMap();
        // String rechargeAmount = param.get("rechargeAmount") == null ? "" : param.get("rechargeAmount").toString();
        //String customAmount = param.get("customAmount") == null ? "" : param.get("customAmount").toString();
        String rechargeAmount = param.getRechargeAmount();
        String customAmount = param.getCustomAmount();
        if (StringUtil.isEmpty(rechargeAmount) && StringUtil.isEmpty(customAmount)) {
            //return getFailureResult(2000, "请确认充值金额");
            //throw new YshopException("请确认充值金额");
            return ApiResult.fail(ErrorEnum.E_100028.getErrorMsg(), data);
        }
        // 充值赠送金额
        String ruleParam = "";
        MtSetting mtSetting = mtSettingService.querySettingByName(BalanceSettingEnum.RECHARGE_RULE.getKey(), storeId);
        if (StringUtil.isNotEmpty(rechargeAmount) && mtSetting != null) {
            if (mtSetting.getValue() != null && StringUtil.isNotEmpty(mtSetting.getValue())) {
                String rules[] = mtSetting.getValue().split(",");
                for (String rule : rules) {
                    String amountArr[] = rule.split("_");
                    if (amountArr.length == 2) {
                        if (amountArr[0].equals(rechargeAmount)) {
                            ruleParam = rule;
                            break;
                        }
                    }
                }
            }
        }

        // 自定义充值没有赠送金额
        if (StringUtil.isEmpty(rechargeAmount)) {
            rechargeAmount = customAmount;
            ruleParam = customAmount + "_0";
        }

        if (StringUtil.isEmpty(ruleParam)) {
            ruleParam = rechargeAmount + "_0";
        }
        MtStore mtStore = storeService.queryStoreById(storeId);
        BigDecimal amount = new BigDecimal(rechargeAmount);
        OrderDto orderDto = new OrderDto();
        orderDto.setType(OrderTypeEnum.RECHARGE.getKey());
        orderDto.setUserId(userId);
        orderDto.setStoreId(storeId);
        orderDto.setAmount(amount);
        orderDto.setUsePoint(0);
        if(mtStore!=null){
            orderDto.setRemark(mtStore.getName()+"会员充值");
        }else{
            orderDto.setRemark("平台通用会员充值");
        }
        orderDto.setParam(ruleParam);
        orderDto.setStatus(OrderStatusEnumV.CREATED.getKey());
        orderDto.setPayStatus(PayStatusEnum.WAIT.getKey());
        orderDto.setPointAmount(new BigDecimal("0"));
        orderDto.setOrderMode("");
        orderDto.setCouponId(0);

        MtOrder orderInfo = mtOrderService.saveOrder(orderDto);

        // MtUser mtUser = memberService.queryMemberById(userInfo.getId());
        //SysXbuser sysXbuser = sysXbuserService.getById(userId);
        YxUser user = userService.getById(userId);
        String ip = CommonUtilV.getIPFromHttpRequest(request);
        BigDecimal pay = amount.multiply(new BigDecimal("100"));
        orderInfo.setPayType(PayTypeEnumV.JSAPI.getKey());
        ResponseObject paymentInfo = weixinService.createPrepayOrder(user, orderInfo, (pay.intValue()), "", 0, ip, PlatformTypeEnum.MP_WEIXIN.getCode());
        //ResponseObject paymentInfo = weixinService.createPrepayOrder(user, orderInfo, pay, "", 0, ip,PlatformTypeEnum.MP_WEIXIN.getCode());
        if (paymentInfo.getData() == null) {
            //return getFailureResult(201, "抱歉，发起支付失败");
            return ApiResult.fail(ErrorEnum.E_100029.getErrorMsg(), data);
        }

        Object payment = paymentInfo.getData();
        data.put("payment", payment);
        data.put("orderInfo", orderInfo);

        // redis发送消息队列，充值升级会员等级,享受预约下单折扣,并有开卡赠礼（赠券）
/*        PublishMessage publishMessage = new PublishMessage();
        publishMessage.setMsgType(2);
        publishMessage.setStoreId(storeId);
        publishMessage.setUserId(userId);
        redisSqueueService.doSomethingAndPublishMessage(publishMessage);*/

        return ApiResult.ok(data);
    }

    /**
     * 查询我的充值记录
     */
    @AppLog(value = "查询我的充值记录", type = 1)
    @AuthCheck
    @PostMapping("/myBalance/list")
    @ApiOperation(value = "查询我的充值记录", notes = "查询我的充值记录")
    public ApiResult<Map<String, Object>> list(HttpServletRequest request, @RequestBody Map<String, Object> param) {
        Map<String, Object> data = new HashMap();
        Long uid = LocalUser.getUser().getUid();
        if (param == null) {
            param = new HashMap<>();
        }
        param.put("userId", uid.intValue());
        ResponseObject result = balanceService.getMyBalanceList(param);
        data.put("myBalanceList", result.getData());
        return ApiResult.ok(data);
    }

    /**
     * 查询用户充值记录
     */
    @AppLog(value = "查询用户充值记录", type = 1)
    @AuthCheck
    @PostMapping("/userBalance/list")
    @ApiOperation(value = "查询用户充值记录", notes = "查询用户充值记录")
    public ApiResult<Map<String, Object>> userBalanceList(HttpServletRequest request, @RequestBody Map<String, Object> param) {

        Map<String, Object> data = new HashMap();

/*      Long uid = LocalUser.getUser().getUid();
        if (param == null) {
            param = new HashMap<>();
        }
        param.put("userId", uid.intValue());
*/

        ResponseObject result = balanceService.getMyBalanceList(param);
        data.put("myBalanceList", result.getData());
        return ApiResult.ok(data);
    }

    /**
     * 充值设置详情
     *
     * @param request
     * @return
     */
    @AppLog(value = "充值设置详情", type = 1)
    // @AuthCheck
    @PostMapping("/balance/setting")
    @ApiOperation(value = "查询充值设置详情", notes = "查询充值设置详情")
    public ApiResult<Map<String, Object>> setting(HttpServletRequest request, @RequestBody TBalanceParam param) {
        //Integer storeId = (request.getParameter("storeId") == null || StringUtil.isEmpty(request.getParameter("storeId"))) ? 0 : Integer.parseInt(request.getParameter("storeId"));
        List<MtSetting> settingList = mtSettingService.getSettingList(SettingTypeEnum.BALANCE.getKey(), param.getStoreId());
        List<RechargeRuleDto> rechargeRuleList = new ArrayList<>();
        String remark = "";
        String status = "";
        if (settingList.size() > 0) {
            for (MtSetting setting : settingList) {
                if (setting.getName().equals(BalanceSettingEnum.RECHARGE_RULE.getKey())) {
                    status = setting.getStatus();
                    String item[] = setting.getValue().split(",");
                    if (item.length > 0) {
                        for (String value : item) {
                            String el[] = value.split("_");
                            if (el.length == 2) {
                                RechargeRuleDto e = new RechargeRuleDto();
                                e.setRechargeAmount(el[0]);
                                e.setGiveAmount(el[1]);
                                rechargeRuleList.add(e);
                            }
                        }
                    }
                } else if (setting.getName().equals(BalanceSettingEnum.RECHARGE_REMARK.getKey())) {
                    remark = setting.getValue();
                }
            }
        }

        Map<String, Object> result = new HashMap();
        result.put("rechargeRuleList", rechargeRuleList);
        result.put("remark", remark);
        result.put("status", status);
        return ApiResult.ok(result);
        //return new ResponseEntity<>(result, HttpStatus.OK);
        //return getSuccessResult(result);
    }

    /**
     * 提交保存-充值设置
     *
     * @param request HttpServletRequest对象
     * @return
     */
    @AppLog(value = "提交保存-充值设置", type = 1)
    //@AuthCheck
    @PostMapping("/balance/saveSetting")
    @ApiOperation(value = "提交保存-充值设置", notes = "提交保存-充值设置")
    //@CrossOrigin
    public ApiResult<String> saveSettingHandler(HttpServletRequest request, @RequestBody Map<String, Object> param) {
        //String token = request.getHeader("Access-Token");
        String status = param.get("status") == null ? StatusEnum.ENABLED.getKey() : param.get("status").toString();
        log.info("status:"+status);
        String remark = param.get("remark") == null ? "" : param.get("remark").toString();
        Integer storeId = Integer.parseInt(param.get("storeId").toString());
        //Integer storeId = (request.getParameter("storeId") == null || StringUtil.isEmpty(request.getParameter("storeId"))) ? 0 : Integer.parseInt(request.getParameter("storeId"));
        List<LinkedHashMap> rechargeItems = (List) param.get("rechargeItem");
        if (rechargeItems.size() < 0) {
            //return getFailureResult(201, "充值规则设置不能为空");
            throw new XunyinException(ErrorEnum.E_100027.getErrorMsg());
        }

        String rechargeRule = "";
        for (LinkedHashMap item : rechargeItems) {
            if (rechargeRule.length() == 0) {
                rechargeRule = item.get("rechargeAmount").toString() + '_' + item.get("giveAmount").toString();
            } else {
                rechargeRule = rechargeRule + ',' + item.get("rechargeAmount").toString() + '_' + item.get("giveAmount").toString();
            }
        }
        log.info("rechargeRule:"+rechargeRule);
        MtSetting setting = new MtSetting();
        setting.setType(SettingTypeEnum.BALANCE.getKey());
        setting.setName(BalanceSettingEnum.RECHARGE_RULE.getKey());
        setting.setValue(rechargeRule);
        setting.setDescription(BalanceSettingEnum.RECHARGE_RULE.getValue());
        setting.setStatus(status);
        setting.setStoreId(storeId);
        //setting.setOperator(accountInfo.getAccountName());
        setting.setUpdateTime(new Date());
        mtSettingService.saveSetting(setting);

        // 保存充值说明
        MtSetting settingRemark = new MtSetting();
        settingRemark.setType(SettingTypeEnum.BALANCE.getKey());
        settingRemark.setName(BalanceSettingEnum.RECHARGE_REMARK.getKey());
        settingRemark.setValue(remark);
        settingRemark.setDescription("");
        settingRemark.setStatus(status);
        settingRemark.setStoreId(storeId);
        //settingRemark.setOperator(accountInfo.getAccountName());
        settingRemark.setUpdateTime(new Date());
        mtSettingService.saveSetting(settingRemark);
        //return new ResponseEntity(HttpStatus.OK);
        return ApiResult.ok("提交成功");
        //return getSuccessResult(true);
    }

}
